//
//  SSStatusRefreshControl.swift
//  MyMicroBlog
//
//  Created by stevenSu on 15/8/4.
//  Copyright © 2015年 stevenSu. All rights reserved.
//

import UIKit

class SSStatusRefreshControl: UIRefreshControl {
    private let refreshThreshold: CGFloat = -131
    private lazy var refreshView: SSStatusRefreshView = SSStatusRefreshView.statusRefreshView()
    
    override init() {
        super.init()
//        backgroundColor = UIColor.redColor()
        
        setupUI()
    }
    
    deinit {
        removeObserver(self, forKeyPath: "frame")
    }
    
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
//        print(frame.origin.y)
        if frame.origin.y > 0 {
            return
        }
        
        if refreshing {
            refreshView.startRefreshing()
        }
        
//        print(frame.origin.y)
        
        if frame.origin.y <= refreshThreshold && !refreshView.statuschanged {
            refreshView.statuschanged = !refreshView.statuschanged
            
        } else if frame.origin.y > refreshThreshold && refreshView.statuschanged{
            refreshView.statuschanged = !refreshView.statuschanged
        }
    }
    
    override func endRefreshing() {
        super.endRefreshing()
        refreshView.finishRefreshing()
    }
    
    

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI() {
        tintColor = UIColor.clearColor()
        addSubview(refreshView)
        refreshView.ff_AlignInner(type: ff_AlignType.CenterCenter, referView: self, size: refreshView.bounds.size)
        addObserver(self, forKeyPath: "frame", options: NSKeyValueObservingOptions(rawValue: 0), context: nil)
    }

}

class SSStatusRefreshView: UIView {
    private var statuschanged = false {
        didSet {
            let angle = statuschanged ? CGFloat(M_PI + 0.01) : CGFloat(M_PI - 0.01)
            UIView.animateWithDuration(0.25, animations: { () -> Void in
                self.arrow.transform = CGAffineTransformRotate(self.arrow.transform, angle)
                self.refreshLabel.text = self.statuschanged ? "释放更新" : "下拉刷新"
            })
        }
    }
    @IBOutlet weak var updateRefreshView: SSStatusRefreshView!
    @IBOutlet weak var arrow: UIImageView!
    @IBOutlet weak var refreshLabel: UILabel!
    @IBOutlet weak var refreshingView: UIImageView!
    
    func startRefreshing() {
        if refreshingView.layer.animationForKey("spin") != nil {
            return
        }
        
        updateRefreshView.hidden = true
        let anim = CABasicAnimation(keyPath: "transform.rotation")
        anim.toValue = 2 * M_PI
        anim.duration = 1
        anim.repeatCount = MAXFLOAT
        refreshingView.layer.addAnimation(anim, forKey: "spin")
        
    }
    
    func finishRefreshing() {
        updateRefreshView.hidden = false
        refreshingView.layer.removeAllAnimations()
    }
    
    class func statusRefreshView() -> SSStatusRefreshView {
        return NSBundle.mainBundle().loadNibNamed("SSStatusRefreshView", owner: nil, options: nil).last as! SSStatusRefreshView
    }
}
